﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Gargoyle.Roton
{
    /// <summary>
    /// An input class designed to be used in conjunction with Windows Forms.
    /// </summary>
    public class BufferInput : Input
    {
        private Queue<Keys> KeyBuffer;
        private Keys PressedKey;

        /// <summary>
        /// Create a new BufferInput.
        /// </summary>
        public BufferInput()
            : base()
        {
            KeyBuffer = new Queue<Keys>();
            PressedKey = Keys.None;
        }

        /// <summary>
        /// Clear the currently pressed key.
        /// </summary>
        public override void ClearPressedKey()
        {
            PressedKey = Keys.None;
        }

        /// <summary>
        /// Get the currently pressed key. This should only be used by Roton internally.
        /// </summary>
        /// <returns>The currently pressed key.</returns>
        public override Keys GetPressedKey()
        {
            return PressedKey;
        }

        /// <summary>
        /// Submit a Key Down event to the interface.
        /// </summary>
        /// <param name="key">The key to submit.</param>
        public override void KeyDown(Keys key)
        {
            Keys keyIndex = key & Keys.KeyCode;

            if (!KeyBuffer.Contains(keyIndex))
            {
                KeyBuffer.Enqueue(keyIndex);
            }

            Ctrl = ((key & Keys.Control) != 0);
            Alt = ((key & Keys.Alt) != 0);
            Shift = ((key & Keys.Shift) != 0);
        }

        /// <summary>
        /// Retrieve the next key from the buffer. This should only be used by Roton internally.
        /// </summary>
        public override void Poll()
        {
            if (KeyBuffer.Count > 0)
                PressedKey = KeyBuffer.Dequeue();
            else
                PressedKey = 0;
        }
    }
}
